package org.ruoyi.chat.service.chat.impl;

import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

/**
 * @author jianxiongliao
 * @date 2025/7/19 18:13
 */
public class DashScopeCompatibleExample {
    private static final String API_KEY = "sk-7dae9a7bcb4c4c239fdd8a55b7ec974c";
    private static final String API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    public static void main(String[] args) {
        // 打印类加载器信息
        System.out.println("OkHttpClient 类加载器: " + OkHttpClient.class.getClassLoader());
        System.out.println("OkHttpClient 类路径: " + OkHttpClient.class.getProtectionDomain().getCodeSource().getLocation());

        // 打印 EventSource 类加载器信息
        System.out.println("EventSource 类加载器: " + EventSource.class.getClassLoader());
        System.out.println("EventSource 类路径: " + EventSource.class.getProtectionDomain().getCodeSource().getLocation());

        // 增加超时时间
        OkHttpClient client = new OkHttpClient.Builder()
//                .connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
//                .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
//                .writeTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .build();

        // 添加 stream 参数
        String requestBody = "{" +
                "\"model\": \"deepseek-r1\"," +
                "\"messages\": [" +
                "{" +
                "\"role\": \"user\"," +
                "\"content\": \"你是谁啊\"" +
                "}" +
                "]," +
                "\"stream\": true" +
                "}";

        // 使用 RequestBody 构造器替代已弃用的方法
        RequestBody body = RequestBody.create(requestBody, MediaType.get("application/json"));

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();

        // 创建 EventSource 工厂
        EventSource.Factory factory = EventSources.createFactory(client);

        // 定义 EventSource 监听器
        EventSourceListener listener = new EventSourceListener() {

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                if (!"[DONE]".equals(data)) {
                    System.out.print(data);
                } else {
                    System.out.println("\n流式响应结束");
                    eventSource.cancel();
                }
            }

            @Override
            public void onClosed(EventSource eventSource) {
                System.out.println("连接已关闭");
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
                if (response != null) {
                    System.out.println("请求失败，状态码: " + response.code());
                }
                if (t != null) {
                    t.printStackTrace();
                }
                eventSource.cancel();
            }
        };

        // 启动 EventSource
        factory.newEventSource(request, listener);

        // 保持主线程运行，避免程序提前退出
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
